<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CategoryController
 *
 * @author Administrator
 */
class CategoryController extends Controller {

    public function actionIndex() {
        $model = new Category();
        //$model->countBySql("select count(1) from vodcms_category where name=1");
        $this->model = &$model;
        $this->performAjaxValidation($model);
       
        if (Yii::app()->request->isPostRequest) {
            $model->attributes = Yii::app()->request->getPost('Category');
             //Cookie::set('category_id', $model->attributes['category_parent_id']);
             Yii::app()->cookies->category_id = $model->attributes['category_parent_id'];
            if ($model->save()) {
                $this->redirect($this->createUrl('index'));
            }
        }
        $model->category_parent_id = Yii::app()->cookies->category_id;
        $this->render("index");
    }

    public function actionEdit() {
        $id = (int) Yii::app()->request->getParam("id");
        $model = new Category();
        $modify = $model->findByPk($id);
        if($modify){
            if (Yii::app()->request->isPostRequest) {
                $modify->attributes = Yii::app()->request->getPost('Category');
                if ($modify->save()) {
                    $this->redirect($this->createUrl('index'));
                }
            }
        }
        $this->render("edit", array('modify' => $modify, 'model' => $model));
    }

    public function actionDel() {
        $model = new Category();
        $id = intval(Yii::app()->request->getParam("id"));
        $category = $model->findByPk($id);
        if ( !$category) {
            $this->render("/layouts/message", array('message' => $model->getAttributeLabel('category_error_404')));
        }  elseif ( $category->delete() === false ) {
            $this->render("/layouts/message", array('message' => $category->getError('category_delete')));
        }else {
            $this->redirect($this->createUrl('index'));
        }
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'category-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionJson() {
        $model = new Category();
        $form = Yii::app()->request->getPost("Category");
        $id = (int) $form['category_parent_id'];
        if ($id > 0) {
            $data = $model->findAll('category_parent_id=:id', array(':id' => $id));
            if ($data) {
                $data = CHtml::listData($data, 'category_id', 'category_name');
                echo CHtml::dropDownList("category_parent_id", "", array_merge(array(""), $data));
            }
        }
    }

}

?>
